/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.GgSydw;
import com.zhuoyue.elmt.entity.MaintenanceContractDevice;
import com.zhuoyue.elmt.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;
import com.zhuoyue.elmt.entity.DeviceParameters;

import java.util.ArrayList;
import java.util.List;

/**
 * 电梯参数查询Controller
 *
 * @author chenhao
 * @version 2016-09-07
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/deviceParameters")
public class DeviceParametersController extends BaseController {

    @Autowired
    private DeviceParametersService deviceParametersService;

    @Autowired
    private MaintenanceContractDeviceService maintenanceContractDeviceService;

    @Autowired
    private GgSbjcService ggSbjcService;

    @Autowired
    private GgSydwService ggSydwService;

    @Autowired
    private CsDtcsService csDtcsService;

    @ModelAttribute
    public DeviceParameters get(@RequestParam(required = false) String tzsbbh) {
        DeviceParameters entity = null;
        if (StringUtils.isNotBlank(tzsbbh)) {
            entity = deviceParametersService.get(tzsbbh);
        }
        if (entity == null) {
            entity = new DeviceParameters();
        }
        return entity;
    }

    /**
     * 查询单条设备信息
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getDeviceParameter/{str1}")
    public String getDeviceParameter(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<DeviceParameters>> resultData = new ResultData();
        List<DeviceParameters> list = new ArrayList();
        try {
            System.out.println("查询单条设备信息 ===========================================>>>>>>>>>>>>>>");
            DeviceParameters record = deviceParametersService.get(str1);
            if (record != null) {
                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的设备信息！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("设备信息查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询单条设备信息
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getDeviceInfoByDeviceCode/{str1}")
    public String getDeviceInfoByDeviceCode(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<DeviceParameters>> resultData = new ResultData();
        List<DeviceParameters> list = new ArrayList();
        try {
            System.out.println("查询单条设备信息 ===========================================>>>>>>>>>>>>>>");
            DeviceParameters qryDeviceParameters = new DeviceParameters();
            qryDeviceParameters.setSbzcdm(str1);
            DeviceParameters record = deviceParametersService.getDeviceInfoByDeviceCode(qryDeviceParameters);
            if (record != null) {
                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的设备信息！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("设备信息查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    // 模糊查询
    @RequestMapping(method = RequestMethod.GET, value = "/getDeviceInfoByDeviceCodeLike/{str1}")
    public String getDeviceInfoByDeviceCodeLike(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<DeviceParameters>> resultData = new ResultData();
        List<DeviceParameters> list = new ArrayList();
        try {
            System.out.println("查询单条设备信息 ===========================================>>>>>>>>>>>>>>");
            DeviceParameters qryDeviceParameters = new DeviceParameters();
            qryDeviceParameters.setSbzcdm(str1);
            qryDeviceParameters.setWbdwdm(UserUtils.getUser().getCompany().getCode());
            qryDeviceParameters.setLoginName(UserUtils.getUser().getLoginName());
            list = deviceParametersService.getDeviceInfoByDeviceCodeLike(qryDeviceParameters);
            if (list != null) {
                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
                resultData.setList(list);
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的设备信息！");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("设备信息查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询多条设备信息
     *
     * @param deviceParameters
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/findDeviceParameter")
    public String findDeviceParameter(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<DeviceParameters>> resultData = new ResultData();
        try {
            System.out.println("查询多条设备信息 ===========================================>>>>>>>>>>>>>>");
            if (!UserUtils.getUser().isAdmin()) {
                deviceParameters.setWbdwdm(UserUtils.getUser().getCompany().getCode());
            }
            deviceParameters.setLoginName(UserUtils.getUser().getLoginName());
            Page<DeviceParameters> page = deviceParametersService.findStaffMainList(new Page<DeviceParameters>(request, response), deviceParameters);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("设备信息查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }


    @RequiresPermissions("elmt:deviceParameters:index")
    @RequestMapping(value = {"index", ""})
    public String index(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        return "zhuoyue/analysis/index";
    }

    @RequiresPermissions("elmt:deviceParameters:analysis")
    @RequestMapping(value = {"nonconformity"})
    public String nonconformity(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DeviceParameters> page = deviceParametersService.findPage(new Page<DeviceParameters>(request, response), deviceParameters);
        model.addAttribute("page", page);
        return "zhuoyue/analysis/nonconformity";
    }

    @RequiresPermissions("elmt:deviceParameters:view")
    @RequestMapping(value = {"list"})
    public String list(String parentIdCach, String contractNo, String contractId, DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!UserUtils.getUser().isAdmin()) {
            deviceParameters.setWbdwdm(UserUtils.getUser().getCompany().getCode());
        }
        if (StringUtils.isNotEmpty(parentIdCach)) {
            if (parentIdCach.equals("58")) {
                model.addAttribute("useUnitId", deviceParameters.getSydwdm());
                model.addAttribute("contractId", contractId);
                model.addAttribute("contractNo", contractNo);
                model.addAttribute("parentIdCach", parentIdCach);
                // request.getSession().setAttribute("useUnitIdCach",deviceParameters.getSydwdm());
                // request.getSession().setAttribute("parentIdCach",parentIdCach);
            }

            if (parentIdCach.equals("78")) {
                model.addAttribute("useUnitId", deviceParameters.getSydwdm());
                model.addAttribute("contractId", contractId);
                model.addAttribute("contractNo", contractNo);
                model.addAttribute("parentIdCach", parentIdCach);
                // request.getSession().setAttribute("useUnitIdCach",deviceParameters.getSydwdm());
                // request.getSession().setAttribute("parentIdCach",parentIdCach);
            }

            if (parentIdCach.equals("98")) {
                model.addAttribute("parentIdCach", parentIdCach);
            }
        }
        Page<DeviceParameters> page = deviceParametersService.findPage(new Page<DeviceParameters>(request, response), deviceParameters);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/deviceParametersList";
    }

    @RequiresPermissions("elmt:deviceParameters:view")
    @RequestMapping(value = {"detail"})
    public String detail(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DeviceParameters> page = deviceParametersService.findPage(new Page<DeviceParameters>(request, response), deviceParameters);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/deviceParametersDetail";
    }

    @RequiresPermissions("elmt:deviceParameters:view")
    @RequestMapping(value = "form")
    public String form(String parentIdCach, DeviceParameters deviceParameters, Model model) {
        model.addAttribute("sydwdm", deviceParameters.getSydwdm());
        deviceParameters.setWbdwdm(UserUtils.getUser().getCompany().getCode());
        if (StringUtils.isEmpty(deviceParameters.getId())) {
            GgSydw qryGgSydw = new GgSydw();
            qryGgSydw.setZzjqdm(deviceParameters.getSydwdm());
            GgSydw ggSydw = ggSydwService.getByCode(qryGgSydw);
            deviceParameters.setSydwmc(ggSydw.getDwmc());

            deviceParameters.setWbdwmc(UserUtils.getUser().getCompany().getName());
        }
        model.addAttribute("parentIdCach", parentIdCach);
        model.addAttribute("deviceParameters", deviceParameters);
        return "zhuoyue/elmt/deviceParametersForm";
    }

    @RequiresPermissions("elmt:deviceParameters:view")
    @RequestMapping(value = "getEquipmentParameter")
    public String getEquipmentParameter(DeviceParameters deviceParameters, Model model) {
        model.addAttribute("deviceParameters", deviceParameters);
        return "zhuoyue/elmt/parametersEquipmentMaintenance";
    }

    @RequiresPermissions("elmt:deviceParameters:edit")
    @RequestMapping(value = "save")
    public String save(String parentIdCach, DeviceParameters deviceParameters, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, deviceParameters)) {
            return form("", deviceParameters, model);
        }
        // deviceParametersService.save(deviceParameters);
        if (StringUtils.isNotEmpty(deviceParameters.getTzsbbh())) {
            ggSbjcService.modifyGgsbjcParameter(deviceParameters);
            csDtcsService.modifyCsDtcsParameter(deviceParameters);
            addMessage(redirectAttributes, "修改设备成功");
        } else {
            deviceParameters.setSbzl("3000");
            deviceParameters.setSbxz("法定设备");
            ggSbjcService.newElevatorParameters(deviceParameters);
            csDtcsService.newElevatorParameters(deviceParameters);
            addMessage(redirectAttributes, "保存设备成功");
        }
        redirectAttributes.addAttribute("sydwdm", deviceParameters.getSydwdm());
        redirectAttributes.addAttribute("parentIdCach", parentIdCach);
        return "redirect:" + Global.getAdminPath() + "/elmt/deviceParameters/list?repage";
    }

    @RequiresPermissions("elmt:deviceParameters:edit")
    @RequestMapping(value = "delete")
    public String delete(String parentIdCach, DeviceParameters deviceParameters, RedirectAttributes redirectAttributes) {
        //deviceParametersService.delete(deviceParameters);
        int success = csDtcsService.deleteCsDtcs(deviceParameters.getTzsbbh());
        if (success > 0) {
            ggSbjcService.deleteGgSbjc(deviceParameters.getTzsbbh());
        }
        addMessage(redirectAttributes, "删除设备成功");
        redirectAttributes.addAttribute("sydwdm", deviceParameters.getSydwdm());
        redirectAttributes.addAttribute("parentIdCach", parentIdCach);
        return "redirect:" + Global.getAdminPath() + "/elmt/deviceParameters/list?repage";
    }

    @RequestMapping(value = {"selectDevice"})
    public String selectDevice(String[] selectDevice, String contractId, String useUnitId, String contractNo, String parentId, HttpServletRequest request, HttpServletResponse response, Model model) {
        MaintenanceContractDevice maintenanceContractDevice = null;
        for (int i = 0; i < selectDevice.length; i++) {
            maintenanceContractDevice = new MaintenanceContractDevice();
            maintenanceContractDevice.setContractNo(contractId);
            maintenanceContractDevice.setDeviceCode(selectDevice[i]);
            maintenanceContractDeviceService.insert(maintenanceContractDevice);
        }

        model.addAttribute("parentId", parentId);
        model.addAttribute("closeWin", "0");
        model.addAttribute("message", "添加设备成功");
        return "zhuoyue/elmt/deviceParametersList";
    }

    @RequiresPermissions("elmt:deviceParameters:view")
    @RequestMapping(value = "getByMaintenanceUnitCode")
    public String getByMaintenanceUnitCode(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
        deviceParameters.setWbdwdm(UserUtils.getUser().getCompany().getCode());
        if (StringUtils.isEmpty(deviceParameters.getState())) {
            deviceParameters.setState("0");
        }
        if (StringUtils.isNotEmpty(deviceParameters.getContractNo()) || StringUtils.isNotEmpty(deviceParameters.getSbzcdm()) || StringUtils.isNotEmpty(deviceParameters.getSydwmc())) {
            deviceParameters.setState("");
        }
        Page<DeviceParameters> page = deviceParametersService.findPageStandby(new Page<DeviceParameters>(request, response), deviceParameters);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/unallocatedEquipmentList";
    }
}